// pages/shopdetails/index.js
const area = require('../../utils/area');
const app = getApp() // 引入app
import _request from '../../utils/request.js'
import {
  getSevenDay,
  getToDay,
  regMobile
} from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    marginBottom: app.globalData.marginBottom,
    imgUrl: app.globalData.imgUrl, //全局img路径
    shopimgUrl: app.globalData.shopimgUrl,
    show: false,
    areaList: '',
    background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    active: 0,
    showlist: [{
        title: '洗吹',
        meney: "99"
      },
      {
        title: '洗吹',
        meney: "99"
      }, {
        title: '洗吹',
        meney: "99"
      },
      {
        title: '洗吹',
        meney: "99"
      }, {
        title: '洗吹',
        meney: "99"
      }
    ],
    evaluatelist: [1, 1, 1, 1, 0.5],
    showLength: 2,
    showtext: true,
    imglist: [{
        id: 1,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 2,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 3,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 4,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
      {
        id: 5,
        imgurl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/header.png'
      },
    ],
    shoplist: null,
    shopltlist: null,
    serverlist: [],
    oldserviceList: [],
    storeStylist: [],
    storeStyobj: null,
    storeCommentList: [],
    evaluation: null,
    score: 0,
    bool: 0,
    page: 1,
    indexs: '',
    shop: '',
    showoverlay: false,
    today: '',
    week: getSevenDay()[0].num,
    datalist: [],
    flag: 0,
    serviceList: [],
  },

  // 去添加精品服务
  onAdd() {
    wx.navigateTo({
      url: '/pages/shopmanager/addqualityservice/index',
    })
  },

  // 获取精品服务列表
  getQualityService() {
    _request.get('/store/getQualityService', {
      storeId: wx.getStorageSync('storeId')
    }).then((res) => {
      // status1平台，0店内
      if (res.data.code === 200) {
        this.setData({
          oldserviceList: res.data.data.map(item => {
              item.flag = 0
              return item
          }),
          serviceList: res.data.data.filter(item => {
            if(this.data.week == item.week){
              item.flag = 0
              return item
            }
          })
        })
      }
      console.log(this.data);
    })
  },

  //点击图片进行预览，长按保存分享图片
  previewImg(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.item, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.item] // 需要预览的图片http链接列表
    })
  },

  //点击轮播图片进行预览，长按保存分享图片
  previewstoreImg(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.item, // 当前显示图片的http链接
      urls: this.data.shopltlist.storePhotos // 需要预览的图片http链接列表
    })
  },

  // 获取服务
  onClickTime_server(e){
    const {
      orderWeek,
      Key,
      num
    } = e.detail
    this.setData({
      serviceList: this.data.oldserviceList.filter(item => {
        if(num == item.week){
          return item
        }
      })
    })
  },
  // 获取点击时间
  onClickTime(e) {
    const {
      orderWeek,
      Key,
      num
    } = e.detail
    const {
      storeStyobj
    } = this.data
    this.setData({
      storeStylist: [],
      week: num,
    })
    let list = []
    if (storeStyobj[Key]) {
      list = storeStyobj[Key].map(item => {
        let distance = (parseInt(item.distance) / 1000).toFixed(2) * 1000;
        let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
        item.zecouponDTOs = item.couponDTOs.filter(item => {
          if (item.type == 2) {
            return item
          }
        })
        item.jiancouponDTOs = item.couponDTOs.filter(item => {
          if (item.type == 1) {
            return item
          }
        })
        if (item.lable) {
          let money = item.lable.match(/\d+(.\d+)?/g).join('');
          let meal = item.lable.split(money)[0]
          return {
            ...item,
            money,
            meal,
            newdistance
          }
        } else {
          return {
            ...item,
            newdistance
          }
        }
      })
    }

    this.setData({
      storeStylist: list,
      today: orderWeek
    })
  },

  // jpactive: function() {
  //   this.setData({
  //     flag: 0 ? 1: 0
  //   })
  // },
  touchStart(e) {
    console.log(e)
    var that = this;
    that.setData({
      touchx: e.changedTouches[0].clientX,
      touchy: e.changedTouches[0].clientY
    })
  },
  touchEnd(e) {
    var that = this;
    let x = e.changedTouches[0].clientX;
    let y = e.changedTouches[0].clientY;
    let turn = "";
    if (x - that.data.touchx > 50 && Math.abs(y - that.data.touchy) < 50) { //右滑
      turn = "right";
    } else if (x - that.data.touchx < -50 && Math.abs(y - that.data.touchy) < 50) { //左滑
      turn = "left";
    }
    if (y - that.data.touchy > 50 && Math.abs(x - that.data.touchx) < 50) { //下滑
      turn = "down";
    } else if (y - that.data.touchy < -50 && Math.abs(x - that.data.touchx) < 50) { //上滑
      turn = "up";
    }
    let list = this.data.serviceList
    const id = e.currentTarget.dataset.id
    list.forEach(ele => {
      if (ele.id == id) {
        ele.flag = turn == 'left' ? 1 : 0
      }
    })
    this.setData({
      serviceList: list
    })
    // //根据方向进行操作
    // if(turn == 'left'){
    //   that.setData({
    //     flag: 1
    //   })
    // }
    // if(turn == 'right'){
    //   that.setData({
    //     flag: 0
    //   })
    // }
  },

  //下架
  goodsdown: function (e) {
    const {
      id,
      status
    } = e.currentTarget.dataset.item;
    let vm = this
    wx.showModal({
      title: '',
      content: status ? '是否要上架该商品' : '是否要下架该商品',
      confirmText: '确认',
      cancelText: '取消',
      success(res) {
        if (res.confirm) {
          _request.postObj('/store/qualityServiceOut', {
            storeId: wx.getStorageSync('storeId'),
            id
          }).then((res) => {
            // console.log(res)
            if (res.data.code === 200 && !status) {
              // 获取精品服务列表
              vm.getQualityService()
              wx.showToast({
                title: '下架成功',
                icon: 'none',
                duration: 1000
              })
              
              
            }else if (res.data.code === 200 && status) {
              // 获取精品服务列表
              vm.getQualityService()
              wx.showToast({
                title: '上架成功',
                icon: 'none',
                duration: 1000
              })
              
              
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
 // 修改
 onedit(e){
  const {
    item
  } = e.currentTarget.dataset;
  let obj = JSON.stringify(item)
  wx.navigateTo({
    url: '/pages/shopmanager/addqualityservice/index?data=' + obj,
  })
 },
  // 资讯

  // 显示电话
  onMobile(e) {
    this.setData({
      showoverlay: true
    })
  },

  // 拨打电话
  goMobile() {
    wx.makePhoneCall({
      phoneNumber: this.data.shoplist.mobile //仅为示例，并非真实的电话号码
    })
  },

  // 隐藏电话
  onClickHide() {
    this.setData({
      showoverlay: false
    })
  },

  // 门店美发师列表
  getstoreStylist(show) {
    if (show) {
      wx.showNavigationBarLoading() // 顶部加载状态
    }
    _request.postObj('/store/storeStylists', {
      storeId: wx.getStorageSync('storeId'),
      size: 10,
      page: 1,
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      this.setData({
        storeStylist: res.data.data.map(item => {
          let distance = (parseInt(item.distance) / 1000).toFixed(2) * 1000;
          let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
          if (item.lable) {
            let money = item.lable.match(/\d+(.\d+)?/g).join('');
            let meal = item.lable.split(money)[0]
            return {
              ...item,
              money,
              meal,
              newdistance
            }
          } else {
            return {
              ...item,
              newdistance
            }
          }
        })
      })
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    }).catch((error) => {
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
      console.log(error, 'error');
    })
  },

  // 门店评论列表
  getstylistComment(e, show) {
    if (show) {
      wx.showNavigationBarLoading() // 顶部加载状态
    }
    _request.get('/storeComment/getStoreCommentList', {
      storeId: wx.getStorageSync('storeId'),
      page: e
    }).then((res) => {
      let list = []
      if (res.data.data && res.data.data != null) {
        list = res.data.data.map(item => {
          item.bool = item.comment.length >= 60 ? true : false;
          return item
        })
        this.setData({
          storeCommentList: e > 1 ? [...this.data.storeCommentList, ...list] : list
        })
      }
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    }).catch((error) => {
      if (show) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
      console.log(error, 'error');
    })
  },


  // 获取tab下标
  onChange(event) {
    this.setData({
      active: event.detail.name
    })
  },


  // 美发师详情
  onDetails(e) {
    const {
      item
    } = e.currentTarget.dataset
    item.active = 0
    let obj = JSON.stringify(item)
    wx.navigateTo({
      url: '/pages/hairstylistdetails/index?hair=' + encodeURIComponent(obj)
    })
  },

  // 前往美发师作品
  toHairstylistproduction(e) {
    const {
      item
    } = e.currentTarget.dataset
    item.active = 1
    let obj = JSON.stringify(item)
    wx.navigateTo({
      url: '/pages/hairstylistdetails/index?hair=' + encodeURIComponent(obj),
    })
  },

  // 预约
  onHairMake(e) {
    const {
      item
    } = e.currentTarget.dataset
    let vm = this
    if (item.week != this.data.week) {
      wx.showModal({
        title: '当前是跨店预约,美发师有可能拒接哦!',
        success(res) {
          if (res.confirm) {
            item.days = getToDay(vm.data.week).orderWeek
            let hair = JSON.stringify(item)
            let shop = JSON.stringify(this.data.shop)
            wx.navigateTo({
              url: '/pages/bookingorder/index?hair=' + encodeURIComponent(hair) + '&shop=' + encodeURIComponent(shop),
            })
          } else if (res.cancel) {}
        }
      })
    } else {
      item.days = getToDay(vm.data.week).orderWeek
      let hair = JSON.stringify(item)
      let shop = JSON.stringify(this.data.shop)
      wx.navigateTo({
        url: '/pages/bookingorder/index?hair=' + encodeURIComponent(hair) + '&shop=' + encodeURIComponent(shop),
      })
    }
  },

  // 查看更多
  toMore(e) {
    const {
      id
    } = e.currentTarget.dataset
    this.setData({
      storeCommentList: this.data.storeCommentList.map(item => {
        if (item.id == id) {
          item.showtext = !item.showtext
        }
        return item
      })
    })
  },

  // 展示更多
  showmore() {
    this.setData({
      showLength: this.data.showlist.length
    })
  },

  // 点击时间高亮
  onitemactive(e) {
    const {
      index
    } = e.currentTarget.dataset
  },

  // 展示3条
  showmuch() {
    this.setData({
      showLength: 2
    })
  },

  // 展示选择城市
  showmolde() {
    this.setData({
      show: true
    });
  },

  // 完成选择城市，发送请求
  onFirm(e) {
    this.setData({
      show: false
    });
  },

  // 展示选择城市
  showPopup() {
    this.setData({
      show: true
    });
  },

  // 关闭选择城市
  onClose() {
    this.setData({
      show: false
    });
  },

  // 轮播
  changeIndicatorDots() {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },

  changeAutoplay() {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },

  intervalChange(e) {
    this.setData({
      interval: e.detail.value
    })
  },


  durationChange(e) {
    this.setData({
      duration: e.detail.value
    })
  },

  // 扫一扫
  getQRCode: () => {
    wx.scanCode({ //扫描API
      success: function (res) {
        var qId = res.result
        if (qId.indexOf("car?id=") != -1) {
          var ids = qId.split("=");
          wx.navigateTo({
            url: "/mainpages/car/index?id=" + ids[1]
          });
        } else if (qId.indexOf("textcard?id=") != -1) {

        } else {
          wx.navigateTo({
            url: "/pages2/qcCodeList/index?qId=" + qId
          });
        }

      },
      fail: function (error) {
        console.log(error); //输出回调信息

      },
    })
  },

  // 点击收藏
  onCollection(e) {
    const {
      storeid
    } = e.currentTarget.dataset
    _request.postObj('/storeManage/updateCollectionType', {
      userId: wx.getStorageSync('userid'),
      storeId: storeid,
      isCollection: this.data.bool
    }).then((res) => {
      this.setData({
        bool: this.data.bool == 1 ? 0 : 1
      })
      wx.showToast({
        title: res.data.message,
        icon: 'none',
        duration: 1000
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  // 修改助理、耗材
  updateMarket() {
    wx.navigateTo({
      url: "/pages/market/index"
    });
  },

  // 获取门店七天得理发师列表
  storeStylistInfos() {
    _request.postObj('/storeStylist/storeStylistInfos', {
      size: 10,
      page: 1,
      storeId: wx.getStorageSync('storeId'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      // 获取当天理发师
      let data = res.data.data
      let today = getSevenDay()[0].Key
      let list = data[today] ? data[today] : []
      this.setData({
        today,
        storeStyobj: res.data.data,
        storeStylist: list.map(item => {
          let distance = (parseInt(item.distance) / 1000).toFixed(2) * 1000;
          let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
          item.zecouponDTOs = item.couponDTOs.filter(item => {
            if (item.type == 2) {
              return item
            }
          })
          item.jiancouponDTOs = item.couponDTOs.filter(item => {
            if (item.type == 1) {
              return item
            }
          })
          if (item.lable) {
            let money = item.lable.match(/\d+(.\d+)?/g).join('');
            let meal = item.lable.split(money)[0]
            return {
              ...item,
              money,
              meal,
              newdistance
            }
          } else {
            return {
              ...item,
              newdistance
            }
          }
        })
      })
    }).catch((error) => {})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      areaList: area.areaList
    })
    // 获取门店七天得理发师列表
    this.storeStylistInfos();
    // 进入页面开始轮播
    this.setData({
      autoplay: true,
    })

    /**
     * 获取助理与耗材
     */
    _request.get('/Consumables/getStoreConsumables', {
      storeId: wx.getStorageSync('storeId')
    }).then((res) => {
      // console.log(res)
      if (res.data.code === 200) {
        this.setData({
          datalist: res.data.data || []
        })
      }
    })

    // 门店顾客评价
    _request.get('/storeManage/getStoreScore', {
      storeId: wx.getStorageSync('storeId'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      let sum = res.data.data.score
      let list = []
      for (let index = 0; index < res.data.data.score; index++) {
        --sum
        list.push(sum)
      }
      this.setData({
        evaluation: list,
        score: res.data.data.score
      })
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 门店服务项目
    _request.get('/storeManage/getStoreServerScope', {
      storeId: wx.getStorageSync('storeId'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      this.setData({
        serverlist: res.data.data.catergoryNames.toString().replace(/,/g, ' | ')
      });
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 门店美发师和评论数统计
    _request.get('/storeManage/storeStylistAndCommentCount', {
      storeId: wx.getStorageSync('storeId'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      this.setData({})
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 门店美发师列表
    this.getstoreStylist(false)
    // 门店评论列表
    this.getstylistComment(1, false)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取精品服务列表
    this.getQualityService()

    // 门店详情
    _request.postObj('/storeManage/getStoreInfo', {
      storeId: wx.getStorageSync('storeId'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      res.data.data.newtelPhone = regMobile(res.data.data.mobile);
      res.data.data.storeSetting.starttime = res.data.data.storeSetting.starttime.substring(0, 5);
      res.data.data.storeSetting.endtime = res.data.data.storeSetting.endtime.substring(0, 5);
      this.setData({
        shoplist: res.data.data,
      })
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 门店位置等信息
    _request.postObj('/storeManage/getStoreInfo', {
      lat: wx.getStorageSync('location').latitude,
      lng: wx.getStorageSync('location').longitude,
      storeId: wx.getStorageSync('storeId'),
      userId: wx.getStorageSync('userid')
    }).then((res) => {
      let distance = (parseInt(res.data.data.distance) / 1000).toFixed(2) * 1000;
      let newdistance = (Math.round(distance * 10) / 10000).toFixed(1)
      this.setData({
        shopltlist: {
          ...res.data.data,
          newdistance
        },
        bool: res.data.data.isCollection
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 离开页面停止轮播
    this.setData({
      autoplay: false,
    })
  },

  edit: function () {
    wx.navigateTo({
      url: "/pages/myprofile/index?from=shopmanager"
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 门店评论列表
    if (this.data.active == 2) {
      this.setData({
        page: this.data.page + 1
      })
      this.getstylistComment(this.data.page, true)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})